<template>
  <div>
    <a-form :model="form" layout="vertical">
      <a-row :gutter="24">
        <a-col v-for="item in renderFormItem" :key="item.field" :span="8">
          <a-form-item
            :field="item.field"
            :label="item.label"
            v-bind="item.formItemProps || {}"
          >
            <component
              :is="item.component"
              v-model="form[item.field]"
              :disabled="dis"
              v-bind="item.componentProps"
              :label-value="form['categoryLv3']"
              :default-query="{
                secretLevel: userSecretLevel,
              }"
              @handleOk="categoryLv3Change"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script setup lang="ts">
  import {
    ref,
    defineProps,
    PropType,
    defineAsyncComponent,
    shallowRef,
    watch,
    computed,
  } from 'vue';
  import lodash from 'lodash';
  import {
    ComponentCfg,
    createDefaultComponents,
  } from '@/common/components/query-form/config';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/basic-configuration/components/procurementquery-form';
  import { useUserStore } from '@/store';
  import { getParentById } from '@/api/Basimanagementapi/categorymanagement';

  const props = defineProps({
    renderKeys: {
      type: Array as PropType<any[]>,
      default: () => [],
    },
    formData: {
      type: Object,
      default: () => {},
    },
    dis: {
      type: Boolean,
      default: false,
    },
    columnNumber: {
      type: Number,
      default: 2,
    },
  });
  const userStore = useUserStore();
  const userSecretLevel = computed(() => userStore.secretLevel || 4);
  const form = ref<any>({});
  const defaultForm: any = {};
  const renderFormItem = ref<any[]>([]); // 最终渲染的组件
  const componentCfg: ComponentCfg = {
    // 所有组件
    ...createDefaultComponents(),
    ...formComponentConfig,
  };
  const emit = defineEmits(['loading']);
  watch(
    () => props.renderKeys,
    () => {
      initRender();
    }
  );
  watch(
    () => props.formData,
    (n) => {
      form.value = n;
    }
  );
  const initRender = () => {
    const renderList: any[] = [];

    props.renderKeys.forEach((key) => {
      const targetCfg = formRenderConfig[key];

      if (targetCfg && componentCfg[targetCfg.componentName]) {
        renderList.push({
          ...targetCfg,
          component: shallowRef(
            defineAsyncComponent(componentCfg[targetCfg.componentName])
          ),
        });
        defaultForm[targetCfg.field] = targetCfg.value;
      }
    });
    renderFormItem.value = renderList;
    form.value = lodash.cloneDeep(defaultForm);
  };
  const categoryLv3Change = async (val: any) => {
    emit('loading', true);
    form.value.categoryLv3Id = val.id;
    form.value.categoryLv3 = val.categoryName;
    form.value.categoryLv3Code = val.categoryCode;
    form.value.categoryLv2Id = val.parentId;
    form.value.categoryLv2 = val.parentCategoryName;
    form.value.categoryLv2Code = val.parentCategoryCode;
    try {
      const res: any = await getParentById({ id: val.parentId });
      if (res.code === 200) {
        const lv1 = res.data;
        form.value.categoryLv1Id = lv1.id;
        form.value.categoryLv1 = lv1.categoryName;
        form.value.categoryLv1Code = lv1.categoryCode;
        emit('loading', false);
      }
    } catch (err: any) {
      console.log(err);
    }
  };
  initRender();
  const getStatus = () => {
    return lodash.cloneDeep(form.value);
  };
  defineExpose({ getStatus });
</script>

<style lang="less" scoped>
  .query-form {
    display: flex;
    width: 100%;
    padding: 20px;
    background: #f7f9fc;
    border-radius: 8px;
  }

  ::v-deep .arco-form-item {
    background: #fff;

    &:focus-within {
      border-color: #165dff;
    }

    .arco-form-item-wrapper-col {
      border: 1px solid #d9dee7;
      border-radius: 3px;
    }

    .arco-picker-size-medium {
      width: 100%;
    }

    .arco-select-view-size-medium {
      width: 100% !important;
    }

    .arco-input-wrapper,
    .arco-picker,
    .arco-select-view-single {
      padding: 0 8px;
      background-color: transparent;
      border-color: transparent;
    }
  }
</style>
